<template>
  <div class="cube-page">
    <header class="header">
      <h2>图片验证码</h2>
      <i @click="navBack"
         class="cubeic-back"></i>
    </header>
    <main class="main-content">
      <cube-input v-model="code"
                  :maxlength="4"
                  placeholder="请输入验证码"></cube-input>
      <div class="imgcode-box">
        <img-verify @getImgCode="getImgCode"
                    ref="imgVerify" />
      </div>

      <div style="margin: 20px 0">
        <cube-button @click="handleClick">提交</cube-button>
      </div>
    </main>
  </div>
</template>

<script>
import ImgVerify from "@/components/ImgVerify";

export default {
  name: "ImgVerifyDemo",
  data() {
    return {
      imgCode: "",
      code: ""
    };
  },
  methods: {
    // 点击图片获取验证码
    getImgCode(code) {
      this.imgCode = code;
    },
    // 点击按钮获取验证码
    handleClick() {
      if (this.code.toLowerCase() === this.imgCode.toLowerCase()) {
        const toast = this.$createToast({
          time: 3000,
          type: "correct",
          txt: "verify success"
        });
        toast.show();
      } else {
        const toast = this.$createToast({
          time: 3000,
          type: "error",
          txt: "verify fail"
        });
        toast.show();
        this.imgCode = this.$refs.imgVerify.draw();
      }
    },
    navBack() {
      this.$router.go(-1);
    }
  },
  components: {
    ImgVerify
  },
  mounted() {
    this.imgCode = this.$refs.imgVerify.draw();
  }
};
</script>
<style scoped>
.main-content {
  padding: 16px;
}
.imgcode-box {
  padding: 12px;
  display: flex;
  justify-content: center;
}
</style>
